#include <cstdlib>
#include <GL/glfw.h>

#include "control/ControlSystem.h"
#include "control/Script.h"
#include "tools/CommandArgs.h"
#include "tools/Log.h"

using namespace std;

bool initialize(const CmdLineArgs& args) {
	return ControlSystem::Instance().init(args);
}

void run() {
	ControlSystem::Instance().update();
}

void Terminate() {
	ControlSystem::Instance().terminate();
	
	glfwTerminate();
}

int WindowClose() {
	std::exit(0);
	return 0;
}

int main(int argc, char **argv)
{
	lout << "> ";
	CmdLineArgs args(argc, argv);		// Parse command line arguments
	
	glfwInit();
	bool ok = glfwOpenWindow(640, 480, 8, 8, 8, 8, 24, 0, GLFW_WINDOW);
	
	if(!ok) {
		Terminate();
		glfwTerminate();
		return 0;
	}
	
	glfwSetWindowTitle("RTS");
	glfwSetWindowPos(50, 50);
	
	if(!initialize(args))
		lout << "ERROR when initializing, deciding to continue..." << endl;
	
	ControlSystem::Instance().setOk(true);
	std::atexit(Terminate);
	glfwSetWindowCloseCallback(&WindowClose);
	
	if (argc > 1)	// User provided a parameter (filename) of file of initial script commands to run
	{
		//Without this we opened up a buffer overflow potential
		if(strlen(argv[1]) > 255) {
			lout << "ERROR: Parameter was too long"<< endl;
			Terminate();
			return 1;
		}
		lout << "Loading " << argv[1] << "..." << endl;
		char initial_cmd[255];
		sprintf(initial_cmd, "load %s", argv[1]);
		Script::process(initial_cmd);
	}
	
	while(ControlSystem::Instance().isOk())
		run();
}
